package com.group.yqxxb.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group.yqxxb.Exception.MyException;
import com.group.yqxxb.dao.UserDao;
import com.group.yqxxb.entity.User;
import com.group.yqxxb.eums.ResultEnum;
import com.group.yqxxb.request.UserCard;
import com.group.yqxxb.service.MessageService;
import com.group.yqxxb.service.UserService;
import com.group.yqxxb.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static final Logger LOG = LoggerFactory.getLogger(MessageService.class);
    ApiUtil apiUtil = new ApiUtil();

    @Autowired
    private UserDao userDao;

    /**
     * 用户注册
     */
    @Override
    @Transactional
    public JSONObject InsertUser(User user) throws Exception{
        //生成特定Header的httpPost
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/create.action");
        //设置请求参数
        //NameValuePair 是名称-值对节点类型多用于java url发送post请求
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid",user.getAccid().toLowerCase()));
        params.add(new BasicNameValuePair("name", user.getName()));
        params.add(new BasicNameValuePair("icon", user.getIcon()));
        params.add(new BasicNameValuePair("token", user.getToken()));
        params.add(new BasicNameValuePair("sign", user.getSign()));
        params.add(new BasicNameValuePair("email", user.getEmail()));
        params.add(new BasicNameValuePair("birth", user.getBirth()));
        params.add(new BasicNameValuePair("mobile", user.getMobile()));
        //如果未null是用toString 报错
        if (user.getGender() != null){
            params.add(new BasicNameValuePair("gender", user.getGender().toString()));
        }

        params.add(new BasicNameValuePair("ex", user.getEx()));

        //设置编码
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        System.out.println(jsonObject);
        if (jsonObject.getInteger("code") == 414){
            LOG.error("注册失败，返回结果："+jsonObject);
            return null;
        }
        JSONObject info = jsonObject.getJSONObject("info");

        LOG.info(user.getAccid());

        String token = info.getString("token");

        user.setToken(token);
        if(jsonObject.getInteger("code") == 200)
        {
            try{
                userDao.InsertUser(user);
            }catch (Exception e){
                throw new MyException(ResultEnum.SQL_ERROR);
            }
        }else if(jsonObject.getInteger("code") == 414 ){
            throw new MyException(ResultEnum.ALREADY_REGISTER);
        }else{
            throw new MyException(jsonObject);
        }
        return jsonObject;
    }

    //更新token
    @Override
    public JSONObject UpdateToken (String accid,String token) throws Exception
    {
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/update.action");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("accid",accid));
        params.add(new BasicNameValuePair("token",token));
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        if(jsonObject.getInteger("code") == 200)
        {
            try{
                userDao.UpdateToken(token, accid);
            }catch (Exception e){
                throw new MyException(ResultEnum.SQL_ERROR);
            }
        }else if (jsonObject.getInteger("code") == 414){
            throw new MyException(ResultEnum.NOT_REGISTER);
        }else{
            throw new MyException(jsonObject);
        }
        return jsonObject;
    }

    //重置token
    @Override
    public JSONObject RefreshToken(String accid) throws Exception{
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/refreshToken.action");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("accid",accid));
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        //获取重置后的token
        JSONObject info = jsonObject.getJSONObject("info");
        String token = info.getString("token");

        if(jsonObject.getInteger("code") == 200)
        {
            try{
                userDao.RefreshToken(accid,token);
            }catch (Exception e){
                throw new MyException(ResultEnum.SQL_ERROR);
            }
        }else if (jsonObject.getInteger("code") == 414){
            throw new MyException(ResultEnum.NOT_REGISTER);
        }else{
            throw new MyException(jsonObject);
        }

        return info;
    }

    //更新用户名片
    @Override
    public boolean UpdateUinfo(UserCard userCard) throws Exception{
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/updateUinfo.action");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid",userCard.getAccid()));
        params.add(new BasicNameValuePair("accid",userCard.getAccid()));
        params.add(new BasicNameValuePair("name", userCard.getName()));
        params.add(new BasicNameValuePair("icon", userCard.getIcon()));
        params.add(new BasicNameValuePair("sign", userCard.getSign()));
        params.add(new BasicNameValuePair("email", userCard.getEmail()));
        params.add(new BasicNameValuePair("birth", userCard.getBirth()));
        params.add(new BasicNameValuePair("mobile", userCard.getMobile()));
        if(userCard.getGender() != null){
            params.add(new BasicNameValuePair("gender", userCard.getGender().toString()));
        }
        params.add(new BasicNameValuePair("ex", userCard.getEx()));
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        if(jsonObject.getInteger("code") == 200)
        {
            try{
                userDao.UpdateUinfo(userCard);
            }catch (Exception e){
                throw new MyException(ResultEnum.SQL_ERROR);
            }
        }else{
            throw new MyException(jsonObject);
        }
        return true;
    }

    //设置桌面端在线时，移动端是否需要推送
    @Override
    public boolean SetDonnop(String accid,String donnopOpen) throws Exception{
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/setDonnop.action");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid",accid));
        params.add(new BasicNameValuePair("donnopOpen",donnopOpen));
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        if (jsonObject.getInteger("code") == 200) {
            return true;
        }else if (jsonObject.getInteger("code") == 414){
            throw new MyException(ResultEnum.NOT_LOGIN_ERROR);
        }else{
            throw new MyException(jsonObject);
        }
    }

    //登录
    @Override
    public String Login(String accid) throws Exception{
        String token;
        try{
            token = userDao.Login(accid);
        }catch (Exception e){
            throw new MyException(ResultEnum.LOGIN_FAIL);
        }
        return token;
    }

    //设置全局禁言
    @Override
    public JSONObject Mute(String accid,Boolean mute) throws Exception{
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/mute.action");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid",accid));
        params.add(new BasicNameValuePair("mute",mute.toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        if (jsonObject.getInteger("code") == 200) {
            return jsonObject;
        }else{
            throw new MyException(jsonObject);
        }
    }

    //获取名片
    @Override
    public JSONArray GetUinfos(JSONArray accids) throws  Exception{
        HttpPost httpPost = apiUtil.BuildHeader("https://api.netease.im/nimserver/user/getUinfos.action");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        if(accids != null || !accids.toString().isEmpty()){
            params.add(new BasicNameValuePair("accids", accids.toString()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
        JSONObject jsonObject = apiUtil.ApiResponse(httpPost);
        if (jsonObject.getInteger("code") == 200){
            JSONArray jsonArray = jsonObject.getJSONArray("uinfos");
            return jsonArray;
        }else{
            throw new MyException(jsonObject);
        }
    }

    /**
     * 查询信息
     */
    @Override
    public User SearchInfo(String accid) throws  Exception{
        User user = userDao.Search(accid);
        if(user==null){
            return null;
        } else{
            user.setToken(null);
        }
        return user;
    };

}
